﻿using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace StableDiffusionTools.Utils
{
    public static class ClipboardUtil
    {
        private const bool defaultKeepAfterExit = true;
        private const int defaultRetryCount = 4;
        private const int defaultRetryDelay = 100;

        public static bool SetText(string txt, bool keepAfterExit = defaultKeepAfterExit, int retryCount = defaultRetryCount, int retryDelay = defaultRetryDelay)
        {
            return SetDataObject(txt, keepAfterExit, retryCount, retryDelay);
        }

        public static bool SetImage(Image img, bool keepAfterExit = defaultKeepAfterExit, int retryCount = defaultRetryCount, int retryDelay = defaultRetryDelay)
        {
            return SetDataObject(img, keepAfterExit, retryCount, retryDelay);
        }

        public static bool SetDataObject(object obj, bool keepAfterExit = defaultKeepAfterExit, int retryCount = defaultRetryCount, int retryDelay = defaultRetryDelay)
        {
            bool result = true;

            try
            {
                Clipboard.SetDataObject(obj, keepAfterExit, retryCount, retryDelay);
            }
            catch (ExternalException)
            {
                result = false;
            }

            return result;
        }
        
        public static bool TryGetText(out string outText, TextDataFormat textDataFormat = TextDataFormat.UnicodeText)
        {
            string outResult = null;
            try
            {
                outResult = Clipboard.GetText(textDataFormat);
            }
            catch (Exception) { }

            outText = outResult;

            return outResult != null;
        }
    }
}
